
/**
\file
Definition of the global lua state with various helper functions.
\author Sean Tromans
*/

#ifndef	SUN_LUA_HPP
#define	SUN_LUA_HPP

#if !defined(SUN_DISABLE_LUA)

#include <sun/lua/lua_fwd.hpp>
#include <sun/lua/exception/exception.hpp>
#include <needs_more_ninja/template/create_string.hpp>

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

#include <luabind/luabind.hpp>
#include <luabind/object.hpp>
#include <luabind/tag_function.hpp>
#include <luabind/operator.hpp>
#include <string>

namespace sun
{

	namespace lua
	{

		/**
		 Exception to throw when an attempt is made to use lua before it is initialised.
		 \author Sean Tromans
		 */
		class not_initialised : public exception
		{
		public:
			not_initialised( std::string const & function_name )
				:	exception( nmn::create_string( "sun::lua::not_initialised: Attempted to use an uninitialised lua_State in function %1%", function_name )  )
			{ }
		};

		/**
		 Exception to throw when an attempt is made to initialise lua more than once.
		 \author Sean Tromans
		 */
		class already_initialised : public exception
		{
		public:
			already_initialised( std::string const & function_name )
				:	exception( nmn::create_string( "sun::lua::already_initialised: Attempted to initialise an already initialise lua_State.\n%1%", function_name )  )
			{ }
		};

		/** Globally accessible lua_State. Probably won't ever get used in this form. */
		extern lua_State * g_state;

		/**
		Creates the lua_State and initialises the engines interface.
		@return false if an error occured during initialisation.
		\throws already_initialised
		\author Sean Tromans
		*/
		bool initialise_state( );

		/**
		Destroys the lua_State.
		\throws not_initialised
		\author Sean Tromans
		*/
		void destroy_state( );

		/**
		Wraps luaL_dostring and handles all error output.
		@param str The string to run through lua.
		@return false if there was any error.
		\throws not_initialised
		\author Sean Tromans
		*/
		bool do_string( std::string const & str );

		/**
		Wraps luaL_dofile and handles all error output.
		@param str The filename of the lua script to run.
		@return false if there was any error.
		\throws not_initialised
		\author Sean Tromans
		*/
		bool do_file( std::string const & str );

	};

};

#endif

#endif	//SUN_LUA_HPP
